<template>
  <div class="login">
    <div class="el-login-content">
      <div class="page">
        <p>
          <span :class="status == true ? 'btnactive btn' : 'btn'"
                @click="status = true">手机登录</span>
          <span :class="status == false ? 'btnactive btn' : 'btn'"
                @click="status = false">邮箱登录</span>
        </p>

        <el-form ref="phoneForm"
                 :model="phoneForm"
                 class="demo-ruleForm"
                 :rules="phoneRule"
                 v-show="status">
          <el-form-item prop="phonenumber"
                        label="手机号">
            <el-input v-model.trim="phoneForm.phonenumber"
                      type="text"
                      @input="phonechange"
                      placeholder="手机号">
            </el-input>
          </el-form-item>
          <el-form-item prop="code"
                        label="验证码">
            <el-input v-model="phoneForm.code"
                      placeholder="验证码"
                      @keyup.enter.native="submitPhone"
                      style="width: 63%">
            </el-input>
            <el-button :class="phonestate?'bgcolor':'bgcolor stop'"
                       :disabled="!phonestate"
                       v-if="!countdown"
                       @click="getCodeData">
              {{countdown1?"重新发送":"获取验证码"}}
            </el-button>

            <el-button class="bgcolor stop"
                       v-if="countdown"
                       :disabled="true">
              {{countdown}} s
            </el-button>
          </el-form-item>

          <div class="fotbtn">
            <el-form-item style="width: 100%">
              <el-button size="medium"
                         type="primary"
                         style="width: 100%"
                         :disabled="!phonestate"
                         :class="phonestate?'bgcolor':'bgcolor stop'"
                         @click="submitPhone">
                登录
              </el-button>
              <div class="fotbtn_f">
                <span></span>
                <div class="signUp"
                     @click="goregister"
                     style="width: 100px;">立即注册</div>
              </div>

            </el-form-item>
          </div>
        </el-form>

        <el-form :model="emailForm"
                 ref="emailForm"
                 :rules="emailRule"
                 class="demo-ruleForm"
                 v-show="!status">
          <el-form-item label="邮箱"
                        prop="email">
            <el-input v-model="emailForm.email"></el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password">
            <el-input type="password"
                      show-password
                      v-model="emailForm.password"
                      @keyup.enter.native="emailLogin"
                      autocomplete="off"></el-input>
          </el-form-item>
          <div class="fotbtn">
            <el-form-item style="width: 100%">
              <el-button size="medium"
                         type="primary"
                         style="width: 100%"
                         @click="emailLogin">
                登录
              </el-button>
              <div class="fotbtn_f">
                <el-checkbox v-model="checked">记住密码</el-checkbox>
                <div>

                  <span class="signUp"
                        @click="goregister">立即注册</span>
                  <span class="signUp"
                        @click="setpassword">忘记密码</span>
                </div>

              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <!--  底部  -->
    <!-- <div class="el-login-footer">

    </div> -->
    <!-- 弹框 -->
    <el-dialog title="提示"
               :visible.sync="dialogVisible"
               width="30%">
      <span>您尚未注册账号，请通过“立即注册”按钮进行注册账号!</span>
      <span slot="footer"
            class="dialog-footer">
        <el-button size="medium"
                   style="background-color: #aa2290; border-color: #aa2290; color: #fff"
                   @click.native.prevent="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 忘记密码弹框 -->
    <el-dialog title="忘记密码"
               :visible.sync="passwordopen"
               width="30%">
      <el-form :model="emailForm"
               ref="emailForm"
               :rules="emailRule"
               class="demo-ruleForm"
               v-show="!status">
        <el-form-item label="邮箱:"
                      prop="email">
          <span>{{emailForm.email}}</span>
        </el-form-item>
        <el-form-item prop="code"
                      label="验证码:">
          <el-input v-model="emailForm.code"
                    placeholder="验证码"
                    @keyup.enter.native="emailverify"
                    style="width: 40%">
          </el-input>
          <el-button class="bgcolor"
                     v-if="!emailcountdown"
                     style="background: #aa2290;color:#fff;margin-left:20px"
                     @click="getCodeEmailData">
            {{emailcountdown1?"重新发送":"获取验证码"}}
          </el-button>
          <el-button class="bgcolor stop"
                     v-if="emailcountdown"
                     :disabled="true"
                     style="background: #ccc;color:#fff;margin-left:20px">
            {{emailcountdown}} s
          </el-button>

        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button size="medium"
                   style="background-color: #aa2290; border-color: #aa2290; color: #fff"
                   @click.native.prevent="emailverify">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 校验密码 -->
    <el-dialog title="修改密码"
               :visible.sync="open"
               width="40%">
      <div>
        <el-form ref="passEmail"
                 :model="passEmail"
                 :rules="passEmailRule"
                 class="register-form phoneform">
          <el-form-item prop="password"
                        label="新密码">

            <el-input type="password"
                      v-model="passEmail.password"
                      autocomplete="off"
                      placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass"
                        label="确认密码">

            <el-input type="password"
                      v-model="passEmail.checkPass"
                      autocomplete="off"
                      placeholder="请再次确认密码"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button size="medium"
                   style="background-color: #aa2290; border-color: #aa2290; color: #fff"
                   @click.native.prevent="passEmailOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { updateCustom } from '@/api/system/custom'
import { isRegister, getCode, getCodeIs } from '@/api/register'
import { setToken } from '@/utils/auth'

export default {
  name: "Login",
  data () {
    const equalToPassword = (rule, value, callback) => {
      if (this.passEmail.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      phonestate: false,
      uuid: "",
      phoneForm: {
        phonenumber: "",
        code: "",
        registerType: 1,
      },
      emailForm: {
        email: "",
        password: "",
        registerType: 2,
      },
      passEmail: {

      },
      status: true, //true==>手机登陆 false==>邮箱登陆
      passEmailRule: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 30, message: '密码长度在8到30个字符之间', trigger: 'blur' },
          // 正则表达式校验
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_])[a-zA-Z\d-_]+$/,
            message: '密码必须包含至少一位大小写字母、数字和符号（-、_）',
            trigger: 'blur'
          }
        ],
        checkPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 30, message: '密码长度在8到30个字符之间', trigger: 'blur' },
          // 正则表达式校验
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_])[a-zA-Z\d-_]+$/,
            message: '密码必须包含至少一位大小写字母、数字和符号（-、_）',
            trigger: 'blur'
          },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
      },
      phoneRule: {
        phonenumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
        code: { required: true, message: "验证码不能为空", trigger: "blur" },
      },
      emailRule: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱格式",
            trigger: ["blur", "change"],

          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          // {
          //   pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[@#$%^&+=!]).{8,30}$/,
          //   message: "请输入8-30个字符，需同时包含数字、字母以及特殊符号",
          //   trigger: "blur",
          // },
        ],
      },
      dialogVisible: false, //手机号弹框
      checked: false,
      redirect: undefined,
      passwordopen: false,
      open: false,
      passForm: {},
      countdown: 0,
      countdown1: 0,
      emailcountdown: 0,
      emailcountdown1: 0,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
        this.uuid = ''
      },
      immediate: true,
    },
    $refs: {
      handler () {
      },
      deep: true,
    },
  },
  created () { },
  methods: {
    passEmailOk () {
      this.$refs.passEmail.validate(valid => {
        if (valid) {
          const params = {
            email: this.emailForm.email,
            password: this.passEmail.password
          }

          updateCustom(params).then(res => {
            if (res.code == 200) {
              this.$alert(
                "<font color='red'>恭喜你，您的账号 " +
                this.emailForm.email +
                "密码修改成功！</font>",
                "系统提示",
                {
                  dangerouslyUseHTMLString: true,
                  type: "success",
                }
              )
                .then(() => {
                  this.open = false
                })
            }
          })

        }
      })
    },
    emailverify () {
      if (!this.emailForm.code) {
        this.$message.error("请先发送验证码在进行操作")
      } else {
        const params = {
          code: this.emailForm.code,
          uuid: this.uuid,
        }
        //校验邮箱验证码是否正确
        getCodeIs(params).then(res => {
          if (res.code == 200) {
            this.open = true
            this.passwordopen = false
          } else {
            this.$message.error("验证码错误")
          }

        })
      }

    },
    phonechange () {
      let reg = /^1[3456789]\d{9}$/
      if (reg.test(this.phoneForm.phonenumber)) {
        isRegister(this.phoneForm).then(res => {
          if (res.code == '200' && res.data > 0) {
            this.phonestate = true
          } else {
            // this.$message.warning("您尚未注册账号，请通过“立即注册”按钮进行注册账号！")
            this.dialogVisible = true
            this.phonestate = false
          }
        })
      } else {
        this.phonestate = false
      }
    },
    goregister () {
      this.$router.push('/register')
    },
    setpassword () {
      const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (regex.test(this.emailForm.email)) {
        isRegister(this.emailForm).then(response => {
          if (response.code == "200" && response.data > 0) {
            //邮箱已被注册，则登录
            this.passwordopen = true
          } else {
            this.$modal.msgError("您尚未注册账号，请通过“立即注册”按钮进行注册账号！");
          }
        })

      } else {
        if (this.emailForm.email) {
          this.$message.error("邮箱格式不正确")
        } else {
          this.$message.error("请输入邮箱地址")
        }

      }

    },
    submitPhone () {
      if (!this.phonestate) {
        this.$message.error("请先输入正确的手机信息")
        return
      }
      var that = this;
      this.$refs.phoneForm.validate((valid) => {
        if (valid && that.phoneForm.code) {
          that.phoneForm.uuid = that.uuid;
          if (that.uuid) {
            that.$store.dispatch("userLogin", that.phoneForm).then(() => {
              this.uuid = ''
              this.$router.push({ path: this.redirect || "/userindex" }).catch(() => { });
            })
          } else {
            this.$message.warning("请先发送验证码在进行登陆")
          }

        }
      })
    },
    getCodeData () {
      this.uuid = ''
      getCode(this.phoneForm).then(response => {
        if (response.code == "200") {
          this.uuid = response.msg;
          if (this.countdown === 0) {
            this.countdown = 60
            this.countdown1 = 120
            const timer = setInterval(() => {
              if (this.countdown > 0) {
                this.countdown--;
              } else {
                clearInterval(timer);
              }
            }, 1000);
            const timer1 = setInterval(() => {
              if (this.countdown1 > 0) {
                this.countdown1--;
              } else {
                clearInterval(timer1);
              }
            }, 1000);
          }
        }
      })
    },

    getCodeEmailData () {
      getCode(this.emailForm).then(response => {
        if (response.code == "200") {
          this.uuid = response.msg;
          if (this.emailcountdown === 0) {
            this.emailcountdown = 60
            this.emailcountdown1 = 120
            const timer = setInterval(() => {
              if (this.emailcountdown > 0) {
                this.emailcountdown--;
              } else {
                clearInterval(timer);
              }
            }, 1000);
            const timer1 = setInterval(() => {
              if (this.emailcountdown1 > 0) {
                this.emailcountdown1--;
              } else {
                clearInterval(timer1);
              }
            }, 1000);
          }
        }
      })
    },
    emailLogin () {
      var that = this;
      const validation = this.$refs.emailForm.validate();
      this.$refs.emailForm.validate((valid) => {
        if (valid) {
          //调用邮箱登陆的接口
          //判断账号是否已经注册
          isRegister(this.emailForm).then(response => {
            if (response.code == "200" && response.data > 0) {
              //邮箱已被注册，则登录
              that.$store.dispatch("userLogin", that.emailForm).then(() => {
                this.$router.push({ path: this.redirect || "/userindex" }).catch(() => { });
              }).catch(() => {
                if (this.captchaEnabled) {
                  this.getCode();
                }
              });

            } else if (response.code == "200" && response.data == 0) {
              //手机号未被注册，则注册
              this.$modal.msgError("您尚未注册账号，请通过“立即注册”按钮进行注册账号！");
            }
          })
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
//
.login {
  /*height: 100%;*/
  /*display: flex;*/
  /*flex-direction: column;*/
  /*position: relative;*/
  /*overflow: hidden;*/
  /*height: 100%;*/

  height: 100%;
  display: flex;
  justify-content: end;
  align-items: center;
  background-image: url("../assets/images/login.png");
  background-size: cover;
  box-sizing: border-box;
  // 登录页面内容区
  .el-login-content {
    width: 100%;
    // height: 810px;
    height: 100%;
    flex: 1;
    background-size: 100% 100%;
    .page {
      width: 28%;
      // height: 454px;
      padding: 40px 38px 53px 40px;
      // position: absolute;
      margin-top: 15%;
      margin-left: 65%;
      background: #ffffff;
      > p {
        display: flex;
        .btn {
          width: 84px;
          height: 22px;
          font-size: 16px;
          font-weight: 400;
          color: #05070a;
          line-height: 22px;
          cursor: pointer;
        }
        .btnactive {
          font-size: 20px;
          font-family: Source Han Sans CN-Bold, Source Han Sans CN;
          font-weight: bold;
          color: #aa2290;
        }
      }
    }
    .demo-ruleForm {
      ::v-deep.el-form-item {
        display: flex;
        flex-direction: column;

        .el-form-item__label {
          text-align: left !important;
        }

        .el-input {
          border-color: #aa2290;
        }
        .bgcolor {
          width: 102px;
          height: 36px;
          background: #aa2290;
          border-radius: 4px 4px 4px 4px;
          opacity: 1;
          float: right;
          padding: 9px 11px 7px;
          line-height: 1;
          border: none;
          color: #fff;
          cursor: pointer;
        }
        .stop {
          background: #ccc;
        }
        p {
          width: 50px;
          height: 22px;
          font-size: 16px;
          margin-bottom: 5px;
        }
      }
    }
  }
}

// 验证码

// 登录按钮
.fotbtn {
  width: 100%;
  height: 80px;
  margin: 40px 0;
  .el-button--primary {
    background-color: #aa2290;
    border-color: #aa2290;
  }
  .fotbtn_f {
    width: 100%;
    display: flex;
    justify-content: space-between;
    ::v-deep.el-checkbox__inner {
      border-radius: 50% !important;
    }
    ::v-deep.is-checked {
      .el-checkbox__inner {
        border-radius: 50% !important;
        background: #aa2290;
      }
    }
    ::v-deep.is-focus {
      outline: none;
    }
  }
  // 注册
  .signUp {
    width: 56px;
    height: 32px;
    line-height: 32px;
    font-size: 14px;
    color: #0b9eae;
    cursor: pointer;
    margin-left: 20px;
  }
  > div {
    display: flex;
    justify-content: space-between;
  }
}
// 底部
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: absolute;
  background-color: #fff;
  bottom: 0px;
  width: 100%;
  text-align: center;
  color: #8c8c8c;

  font-family: 806 Typography-806 Typography, 806 Typography;
  font-size: 16px;
  letter-spacing: 1px;
}

// 穿透全局样式
::v-deep.el-button-text {
  color: none;
}
</style>
